package com.fzrskj.cloud.free.api;

import com.fzrskj.cloud.free.core.tool.CDateTimeTool;
import com.fzrskj.cloud.free.core.tool.CEncryptTool;
import com.fzrskj.cloud.free.core.tool.CHttpTool;
import com.fzrskj.cloud.free.dic.utils.DicParamUtils;
import com.fzrskj.cloud.free.user.bean.UserCharge;
import com.fzrskj.cloud.free.user.utils.UserChargeUtils;
import ms.core.consts.SysErr;
import ms.core.object.CObject;
import ms.core.tool.HttpTool;
import ms.core.tool.StrTool;
import net.sf.json.JSONObject;
import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

public class AlipayAPI extends CObject {
	
	public String alipayWiniis(String params) {
		JSONObject obj_result = new JSONObject();
		JSONObject json = JSONObject.fromObject(params);
		
		String amount=new java.text.DecimalFormat("#.00").format(json.get("amount"));
		String userName = json.getString("uname");	
		int uId = json.getInt("uid");
		
		String format = "yyyyMMddHHmmss";
		String now = CDateTimeTool.formatDateTime(new Date(),format);
		
		String winiisUrl = "http://www.winiis.com/tools/alipay/alipay_gateway.asp";
		String result = "";
		
		String alipayaccount = DicParamUtils.getParamValue("alipayac");
		String alipaycomweb = DicParamUtils.getParamValue("alipaycomweb"); 
		if (StrTool.isBlankStr(alipaycomweb)||StrTool.isBlankStr(alipaycomweb)) {
			obj_result.put("code", "-1");
			obj_result.put("message", "接口未配置");
		    return obj_result.toString();
		}
		String itemsURL = "http://www.winiis.com/tools/alipay/alipay_getpaners.asp?";
		String url=alipaycomweb + "/alipay_return";
		itemsURL=itemsURL + "url=" +url+ "&email=" + alipayaccount + "&pamer=saykey";

		HttpTool http = new HttpTool();
		String saykey = http.httpGet(itemsURL);
		if (saykey.equals("-1")) {
			obj_result.put("code", "-1");
			obj_result.put("message", "您目前无法使用支付宝充值，请联系客服。");
		    return obj_result.toString();
		}
		http=null;

		now = now+saykey;
		if(!("".equals(alipayaccount) || "".equals(userName))){
			StringBuffer param = new StringBuffer("_input_charset=UTF-8"
					+"&body="+userName+" recharge "+amount					//交易内容
					+"&notify_url="+alipaycomweb+"/alipay_receive"			//服务器异步通知页面路径
					+"&out_trade_no="+ now									//商户网站唯一订单号
					+"&payment_type=1"										//支付类型    1:商品购买
					+"&return_url="+alipaycomweb+"/alipay_return"			//页面跳转同步通知页面路径
					+"&seller_email="+alipayaccount							//支付宝收款账号
					+"&service=create_direct_pay_by_user"					//接口名称
					+"&show_url="+alipaycomweb								//商品展示网址
					+"&sign_type=MD5"
					+"&subject="+now
					+"&total_fee="+json.get("amount"));						//金额
			if (json.get("orderId") != null) {
				param.append("&extra_common_param="+json.get("orderId"));
			}

			result = winiisUrl+"?"+param.toString();
			obj_result.put("code", "1");
			obj_result.put("message", "成功");
			obj_result.put("data", result);
			obj_result.put("paychannel", "alipay");
		}

		//插入充值记录

		UserChargeUtils userChargeUtils = new UserChargeUtils();
		UserCharge userCharge = new UserCharge();
		userCharge.setUserName(userName);
		userCharge.setUserId(uId);
		userCharge.setAmount(Double.valueOf(amount));
		userCharge.setBankCode("alipay");
		userCharge.setStatus("N");
		userCharge.setOrderId(now);
		userCharge.setRegTime(new Date());
		userChargeUtils.addUserCharge(userCharge);
		userChargeUtils.dispose();
		String code = userChargeUtils.getErrCode();
		if (!code.equals(SysErr.CODE_SUCCESS)){
			obj_result.put("code", "-1");
			obj_result.put("message", "充值失败,无法添加充值记录。");
		    return obj_result.toString();
		}

		return obj_result.toString();
	}

	public String alipay(String params, Integer agentId) {
		JSONObject obj_result = new JSONObject();
		JSONObject json = JSONObject.fromObject(params);
		String amount=new java.text.DecimalFormat("#.00").format(json.get("amount"));
		UserChargeUtils userChargeUtils = new UserChargeUtils();
		String alipayUrl = "https://mapi.alipay.com/gateway.do";
		String result = "";

		String alipayaccount = DicParamUtils.getParamValue("alipayac", agentId);
		String alipaycomweb = DicParamUtils.getParamValue("alipaycomweb", agentId);
		String alipaypartnerid = DicParamUtils.getParamValue("alipaypartnerid", agentId);
		String alipaykey = DicParamUtils.getParamValue("alipaykey", agentId);
		if (StrTool.isBlankStr(alipaycomweb)||StrTool.isBlankStr(alipaycomweb)||
				StrTool.isBlankStr(alipaypartnerid)||StrTool.isBlankStr(alipaykey)) {
			obj_result.put("code", "-1");
			obj_result.put("message", "接口参数不全[alipayac:"+alipayaccount+"][alipaycomweb:"+alipaycomweb+
					"][alipaypartnerid:" + alipaypartnerid + "][alipaykey:"+alipaykey+"]");
		    return obj_result.toString();
		}
		String userName = json.getString("uname");
		int uId = json.getInt("uid");

		String format = "yyyyMMddHHmmss";
		String now = "";

		if(!("".equals(alipayaccount)||"".equals(alipaypartnerid)||"".equals(alipaykey)||"".equals(userName))){
			now = CDateTimeTool.formatDateTime(new Date(),format);
			String antiKey = getanti_phishing_key(alipaypartnerid);
			if (StrTool.isBlankStr(antiKey)) {
				obj_result.put("code", "-1");
				obj_result.put("message", "生成支付信息失败，可能是支付商户信息不正确！");
				return obj_result.toString();
			}
			StringBuffer param = new StringBuffer("_input_charset=UTF-8"
					+"&anti_phishing_key="+getanti_phishing_key(alipaypartnerid)	//防钓鱼时间戳
					+"&body="+userName+" recharge "+amount							//交易内容
					+"&exter_invoke_ip="+json.getString("Ip"));						//IP
			if (json.get("orderId") != null) {
				param.append("&extra_common_param=" + json.get("orderId"));
			}
			param.append("&notify_url="+alipaycomweb+"/alipay_receive"				//服务器异步通知页面路径
					+"&out_trade_no="+now											//商户网站唯一订单号
					+"&partner="+alipaypartnerid									//合作者身份ID
					+"&payment_type=1"												//支付类型    1:商品购买
					+"&return_url="+alipaycomweb+"/alipay_return"					//页面跳转同步通知页面路径
					+"&seller_email="+alipayaccount									//支付宝收款账号
					+"&service=create_direct_pay_by_user"							//接口名称
					+"&show_url="+alipaycomweb										//商品展示网址
					+"&subject="+now
					+"&total_fee="+json.get("amount"));								//金额

			param.append("&sign_type=MD5&sign="+ CEncryptTool.md5Encode(param.toString()+alipaykey));
			result = alipayUrl + "?" + param.toString();
			obj_result.put("code", "1");
			obj_result.put("message", "成功");
			obj_result.put("data", result);
			obj_result.put("paychannel", "alipay");
		}

		//插入充值记录
		UserCharge userCharge = new UserCharge();
		userCharge.setUserName(userName);
		userCharge.setUserId(uId);
		userCharge.setAmount(Double.valueOf(amount));
		userCharge.setBankCode("alipay");
		userCharge.setStatus("N");
		userCharge.setOrderId(now);
		userCharge.setRegTime(new Date());
		userCharge.setFromAgentUserId(agentId);
		userChargeUtils.addUserCharge(userCharge);
		String code = userChargeUtils.getErrCode();
		userChargeUtils.dispose();
		if (!code.equals(SysErr.CODE_SUCCESS)){
			obj_result.put("code", "-1");
			obj_result.put("message", "充值失败,无法添加充值记录。");
		    return obj_result.toString();
		}
		return obj_result.toString();
	}
	
	private String getanti_phishing_key(String partner){
		CHttpTool http = new CHttpTool();
		String result = "";
		String url = "https://mapi.alipay.com/gateway.do";
		List<NameValuePair> params = new ArrayList<NameValuePair>();
		params.add(new BasicNameValuePair("service", "query_timestamp"));
		params.add(new BasicNameValuePair("partner",partner));
		params.add(new BasicNameValuePair("input_charset","UTF-8"));
		result=http.httpPost(url,params,"utf-8");
		if (result.indexOf("<encrypt_key>") < 0) {
			return null;
		}
		int begin = result.indexOf("<encrypt_key>")+"<encrypt_key>".length();
		int end = result.indexOf("</encrypt_key>");
		String anti_phishing_key = result.substring(begin, end);
		http.dispose();
		return anti_phishing_key;	
	}
	
	public String alipayNotifyVerify(String notifyId) {
		CHttpTool http = new CHttpTool();
		String result = "";
		String alipaypartnerid = DicParamUtils.getParamValue("alipaypartnerid");
		String apliyUrl = "https://mapi.alipay.com/gateway.do";
		List<NameValuePair> params = new ArrayList<NameValuePair>();
		params.add(new BasicNameValuePair("service", "notify_verify"));
		params.add(new BasicNameValuePair("partner",alipaypartnerid));
		params.add(new BasicNameValuePair("notify_id",notifyId));
		result = http.httpPost(apliyUrl,params,"utf-8");
		http.dispose();
		return result;
	}
}
